import os.path
import threading
import keyboard
from tools.beep import beep

from tools.mouse_state_recorder import run as run__mouse_state_recorder, MouseStateRecorder
from tools.key_state_recorder import run as run__key_recorder, KeyStateRecorder
from tools.screen_recorder import run as run__screen_recorder, ScreenRecorder

from tools.use_key_state_move_mouse import run as run__key_move_mouse

# from tools.enum_window import get_hwnd_by_enum, get_title_bar_size, move_wind_to_left_top, bring_window_to_top
from tools.enum_window import set_genshin_window_position
from tools import ms
from tools.abs_mouse_recorder import play_record as play_abs_mouse_record
from tools import kk
from bdtime import Time

from tools.mouse_state_recorder import DefaultArgs
from tools.image_utils import AutoEnterAndExit
from tools.beep import end_beep
from bdtime import Time


def run(save_file_name, flag__remove_file=False):
    use_screen_recorder = True

    tt = Time()
    mouse_state_recorder = MouseStateRecorder(tt=tt)
    key_state_recorder = KeyStateRecorder(tt=tt)
    screen_recorder = ScreenRecorder(tt=tt, save_file_name=None, operation_file_name=save_file_name,
                                     wait_start_flag=True, check_stop_flag=True)

    if flag__remove_file:
        tt.tqdm_sleep(f'准备清除已有记录[{save_file_name}]!')
        for instance in [mouse_state_recorder, key_state_recorder, screen_recorder]:
            save_file_path = instance.get_save_file_path(save_file_name)
            if os.path.exists(save_file_path):
                from tools.remove_temp_file import remove_path
                remove_path(save_file_path)
        beep()
        exit()

    has_genshin_window = set_genshin_window_position()

    if has_genshin_window:
        auto_enter_and_exit = AutoEnterAndExit()

    exists_save_file = False
    if os.path.exists(mouse_state_recorder.get_save_file_path(save_file_name)):
        exists_save_file = True

    play_target = True if exists_save_file else False
    play_recorded_states = True if exists_save_file else False

    remove_else_recoded = False

    # hotkey = 'alt + `'
    # print(f'--- wait hotkey[{hotkey}]!')
    # keyboard.wait(hotkey)

    tt.sleep(0.5)
    print('--- start mouse and key recorder!')
    beep(t=0.3)

    if has_genshin_window:
        try:
            auto_enter_and_exit.enter_test_self()
        except Exception as e:
            beep(v=400, t=0.5)
            raise e

    tt.__init__()

    DefaultArgs.flag__exit = False
    DefaultArgs.flag__start_screen_record = False
    DefaultArgs.flag__stop_screen_record = False

    def end_call():
        DefaultArgs.flag__stop_screen_record = True

    mouse_kwargs = {
        'save_file_name': save_file_name,
        'play': play_recorded_states,
        'remove_else_recoded': remove_else_recoded,
        'play_target': play_target,
        'end_call': end_call,
        # 'tt': tt,
        'mouse_state_recorder': mouse_state_recorder,
    }
    task_mouse = threading.Thread(target=run__mouse_state_recorder, kwargs=mouse_kwargs)

    key_kwargs = {
        'save_file_name': save_file_name,
        'play': play_recorded_states,
        'remove_else_recoded': remove_else_recoded,
        'play_target': play_target,
        # 'tt': tt,
        'end_call': end_call,
        'key_state_recorder': key_state_recorder,
    }
    task_key = threading.Thread(target=run__key_recorder, kwargs=key_kwargs)

    km_kwargs = {
        'tt': tt,
    }
    task_km = threading.Thread(target=run__key_move_mouse, kwargs=km_kwargs)

    if use_screen_recorder:
        km_kwargs = {
            # 'save_file_name': screen_video_dir_name,
            # 'tt': tt,
            'screen_recorder': screen_recorder,
        }
        task_screen_recorder = threading.Thread(target=run__screen_recorder, kwargs=km_kwargs)
        task_screen_recorder.start()

    task_mouse.start()
    task_key.start()
    task_km.start()

    task_key.join()
    task_mouse.join()

    if has_genshin_window:
        kk.press_and_release('alt')

        try:
            auto_enter_and_exit.exit_test_self()
        except Exception as e:
            beep(v=400, t=0.5)
            print('auto_enter_and_exit.exit_test_self --- error:', e)

        keyboard.press_and_release('win + d')

    DefaultArgs.flag__exit = True

    end_beep()

    tt.sleep(1)
    return


if __name__ == '__main__':
    # save_file_name = 'cao_shen__play'
    save_file_name = 'cao_shen__0'

    flag__remove_file = False
    # flag__remove_file = True
    run_times = 10

    # run(save_file_name, flag__remove_file=flag__remove_file)

    f_kwargs = {
        'save_file_name': save_file_name,
        'flag__remove_file': flag__remove_file,
    }

    t1 = Time()
    for i in range(run_times):
        # run(save_file_name, flag__remove_file=flag__remove_file)
        task = threading.Thread(target=run, kwargs=f_kwargs)
        task.start()
        task.join()

        print(f'=========== run: {i}\n')
        t1.sleep(1)

    beep(600, 0.2)
    # beep(800, 0.2)

